﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;

namespace Common.Utility
{
    public class ExcelHelper
    {
        #region Excel下载
        /// <summary>
        /// 根据DataTable数据自动生成Excel数据字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetExcelString(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();


            //定义表对象与行对象，同时用DataSet对其值进行初始化 
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            int cl = dt.Columns.Count;


            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加\n
                {
                    sb.Append(dt.Columns[i].Caption.ToString() + "\n");
                }
                else
                {
                    sb.Append(dt.Columns[i].Caption.ToString() + "\t");
                }

            }


            //逐行处理数据   
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列，加\n
                    {
                        sb.Append(row[i].ToString() + "\n");
                    }
                    else
                    {
                        sb.Append(row[i].ToString() + "\t");
                    }

                }
            }
            return sb.ToString();

        }

        /// <summary>
        /// 根据DataTable数据生成Excel文件并下载
        /// </summary>
        /// <param name="dt"></param>
        public static void DownLoadExcel(DataTable dt)
        {
            string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
            string excel = GetExcelString(dt);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            HttpContext.Current.Response.Write(excel);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        #endregion

        #region 读取Excel
       
        /// <summary>
        /// 获取所有的工作表名称
        /// </summary>
        /// <returns></returns>
        public static List<string> GetSheets(string fpath)
        {
            List<string> list = new List<string>();
            string connString = GetConnString(fpath);
            OleDbConnection conn = new OleDbConnection(connString);
            try
            {
                conn.Open();
                DataTable table = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                conn.Close();
                foreach (DataRow row in table.Rows)
                {
                    list.Add(row[2].ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        /// <summary>
        /// 读取Excel文件到DataTabel
        /// </summary>
        /// <param name="fpath">Excel文件绝对路径</param>
        /// <param name="sheet">工作簿名称</param>
        /// <param name="hdr">第一行是否为标题</param>
        /// <returns></returns>
        public static DataTable ReadExcel(string fpath, string sheet)
        {
            DataTable dt = new DataTable();
            string connString = GetConnString(fpath);
            OleDbDataAdapter ada = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheet), connString);
            ada.Fill(dt);
            return dt;
        }

        /// <summary>
        /// 根据Excel文件自动生成相应的链接字符串
        /// </summary>
        /// <param name="fpath"></param>
        /// <returns></returns>
        private static string GetConnString(string fpath)
        {
            string ext = Path.GetExtension(fpath).ToLower();
            string connString = null;
            if (ext.ToLower() == ".xls")
            {
                connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", fpath);
            }
            else
            {
                connString = string.Format("Provider=Microsoft.ace.oledb.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'", fpath);
            }

            return connString;
        }

        #endregion
    }
}
